package io.github.wanggit.antrpc.commons.codec;

import io.github.wanggit.antrpc.commons.bean.RpcProtocol;
import io.github.wanggit.antrpc.commons.bean.RpcProtocolBuilder;
import io.github.wanggit.antrpc.commons.codec.cryption.ICodec;
import io.github.wanggit.antrpc.commons.constants.ConstantValues;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RpcProtocolDecoder extends LengthFieldBasedFrameDecoder {

    private final ICodec codec;

    public RpcProtocolDecoder(ICodec codec) {
        super(
                ConstantValues.DECODER_MAX_FRAME_LENGTH,
                ConstantValues.DECODER_LENGTH_FIELD_OFFSET,
                ConstantValues.DECODER_LENGTH_FIELD_LENGTH,
                ConstantValues.DECODER_LENGTH_ADJUSTMENT,
                ConstantValues.DECODER_INITIAL_BYTES_TO_STRIP);
        this.codec = codec;
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
        RpcProtocol rpcProtocol = RpcProtocolBuilder.build(byteBuf);
        if (null == rpcProtocol) {
            return null;
        }
        if (rpcProtocol.getType() == ConstantValues.HB_TYPE) {
            return rpcProtocol;
        } else if (rpcProtocol.getType() == ConstantValues.BIZ_TYPE) {
            RpcProtocolBuilder.unzipAndDecodec(rpcProtocol, codec);
            return rpcProtocol;
        }
        return null;
    }
}
